﻿#region references
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

/* Project dependencies */
using IcaGames.Objects;
using IcaGames.Database.ObjectManagement;
using IcaGames.Security;
using System.Web;
#endregion

public partial class Account : System.Web.UI.Page
{
    #region public attributes
    public List<ShoppingCart> _savedCarts
    {
        set { ViewState["savedCart"] = value; }
        get
        {
            List<ShoppingCart> ret = null;
            if (ViewState["savedCart"] != null)
                ret = (List<ShoppingCart>)ViewState["savedCart"];
            return ret;
        }
    }
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (!Page.User.Identity.IsAuthenticated)
            {
                pnlContent.Visible = false;
                pnlLogin.Visible = true;
            }
            else
            {
                pnlLogin.Visible = false;
                pnlContent.Visible = true;
                GetUserDownloads();
            }
        }
    }

    /*
     * Function to get the downloads that are available to the user.
     */
    private void GetUserDownloads()
    {
        CustomMembershipProvider provider = Membership.Provider as CustomMembershipProvider;
        int userId = provider.GetUserId(Page.User.Identity.Name);
        List<ShoppingCart> cart = CartManagement.GetShoppingCarts(userId, "Ja");
        _savedCarts = cart;

        if (cart.Count > 0)
        {
            List<Game> downloads = new List<Game>();
            foreach (ShoppingCart c in cart)
            {
                c.Games = CartManagement.GetShoppingCartGames(c.CartId);
                if (c.Games != null)
                {
                    foreach (Game g in c.Games)
                    {
                        if (g.Downloads != 0) 
                        {
                            if ((DateTime.Compare(DateTime.Now, g.DownloadLimit) < 0))
                            {
                                g.CartId = c.CartId;
                                downloads.Add(g); 
                            }
                        }
                    }
                }
            }

            gvDownloads.DataSource = downloads;
            gvDownloads.DataBind();
        }
    }

    /*
     * Function that switches the MultiView control to ActiveViewIndex 0.
     */
    protected void ToDownloads(object sender, EventArgs e)
    {
        MultiView1.ActiveViewIndex = 0;
        lbDownloads.Enabled = false;
        lbOrderHistory.Enabled = true;
    }

    /*
     * Function that switches the MultiView control to ActiveViewIndex 1.
     */
    protected void ToOrderHistory(object sender, EventArgs e)
    {
        MultiView1.ActiveViewIndex = 1;
        lbDownloads.Enabled = true;
        lbOrderHistory.Enabled = false;

        gvOrderHistory.DataSource = _savedCarts;
        gvOrderHistory.DataBind();
    }

    /*
     * Event that is fired when the GridView gvOrderHistory is rendered.
     */
    protected void gvOrderHistory_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton lbOrderId = e.Row.FindControl("lbOrderId") as LinkButton;
            Label lblCartAmount = e.Row.FindControl("lblCartAmount") as Label;
            Label lblCartTotalPrice = e.Row.FindControl("lblCartTotalPrice") as Label;
            Label lblOrderDate = e.Row.FindControl("lblOrderDate") as Label;

            if (lbOrderId != null && lblCartAmount != null && lblCartTotalPrice != null)
            {
                CustomMembershipProvider provider = Membership.Provider as CustomMembershipProvider;
                int userId = provider.GetUserId(Page.User.Identity.Name);
                List<ShoppingCart> cart = CartManagement.GetShoppingCarts(userId, "Ja");
                int totalAmount = 0;
                decimal totalPrice = 0;

                foreach (ShoppingCart c in cart)
                {
                    c.Games = CartManagement.GetShoppingCartGames(c.CartId);
                    if (c.CartId == int.Parse(lbOrderId.Text))
                    {
                        foreach (Game g in c.Games) { totalAmount += g.Amount; totalPrice += g.Price * g.Amount; }
                    }
                }

                lblCartAmount.Text = totalAmount.ToString();
                lblCartTotalPrice.Text = "€ " + String.Format("{0:0,##}", totalPrice.ToString().Replace('.', ','));
            }

            if (lblOrderDate != null)
            {
                DateTime tempDownloadLimit = DateTime.Parse(lblOrderDate.Text);
                lblOrderDate.Text = tempDownloadLimit.ToString("dd-MM-yyyy HH:mm:ss");
            }
        }
    }

    /*
     * Event that is fired when the GridView gvDownloads is rendered.
     */
    protected void gvDownloads_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblGameDownloadLimit = e.Row.FindControl("lblGameDownloadLimit") as Label;
            if (lblGameDownloadLimit != null)
            {
                DateTime tempDownloadLimit = DateTime.Parse(lblGameDownloadLimit.Text);
                lblGameDownloadLimit.Text = tempDownloadLimit.ToString("dd-MM-yyyy HH:mm:ss");
            }
        }
    }

    /*
     * Function to download the selected game.
     */
    protected void DownloadGame(object sender, EventArgs e)
    {
        if (Page.User.Identity.IsAuthenticated)
        {
            LinkButton lbDownloadGame = sender as LinkButton;
            if (lbDownloadGame != null)
            {
                CustomMembershipProvider provider = Membership.Provider as CustomMembershipProvider;
                int userId = provider.GetUserId(Page.User.Identity.Name);
                Session["download"] = userId;

                string[] param = lbDownloadGame.CommandArgument.Split('_');
                Response.Redirect("~/controls/webhandler/DownloadHandler.ashx?" + 
                    "g=" + param[0] + "_" + param[1] +
                    "&u=" + userId +
                    "&o=" + param[2]);
            }
        }
    }
}
